<!-- 被申请人答复 -->
<template>
  <a-card class="case_produce" :bordered="false">
    <div style="margin-bottom: 15px">
      <span class="add_form_label">{{ labelTitle }}</span>
      <!-- 非中止情况展示这一个按钮 -->
      <a-button
        @click="activeBtnClick"
        type="primary"
        class="add_form_btn"
        v-show="operateBtnShow"
        :disabled="operateBtnDisabled"
      >
        {{ btnLabel }}
      </a-button>
      <!-- :disabled="btnDisabled"  -->
      <a-button class="add_form_btn" type="primary" disabled> 发起申请 </a-button>
      <!-- 当前是编辑模式 -->
      <a-button v-if="isEditModel" class="add_form_btn" @click="addCustomerMaterial"> 新增自定义材料 </a-button>
      <a-divider />
    </div>
    <div style="margin: 10px 10px">
      <a-form layout="inline">
        <a-form-item label="被申请人 ：">
          <!--  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" -->
          <!-- <a-select
            v-model="selectPersons"
            style="width: 400px; font-weight: normal"
            placeholder="请选择被申请人"
            allowClear
          >
            <a-select-option v-for="targetOrg in targetOrgData" :key="targetOrg.id" :value="targetOrg.id">
              {{
                targetOrg.name +
                (targetOrg.agenter ? '-' + targetOrg.agenter : '') +
                (targetOrg.phone ? '-' + targetOrg.phone : '')
              }}
            </a-select-option>
          </a-select> -->
          <a-radio-group v-model="selectPersons" name="radioGroup" :default-value="1">
            <a-radio v-for="targetOrg in targetOrgData" :key="targetOrg.id" :value="targetOrg.id">
              <span style="font-size: 16px">
                {{
                  targetOrg.name +
                  (targetOrg.agenter ? '-' + targetOrg.agenter : '') +
                  (targetOrg.phone ? '-' + targetOrg.phone : '')
                }}</span
              >
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </div>
    <a-list class="file_list" item-layout="horizontal" :data-source="fileItem">
      <a-list-item slot="renderItem" slot-scope="item">
        <a-list-item-meta style="margin-top: 10px">
          <span slot="title">
            <div v-if="!item.isCustomer">
              <span v-if="item.required" style="color: red; padding-right: 5px; text-align: center">*</span>
              <span v-else style="padding-right: 10px"></span>
              <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
              <div class="file_title">
                <span class="upload_span">{{ item.fileName }}</span>
                <a
                  style="color: #0072c6;margin-left: 10px;"
                  class="upload_btn btn_normal_color"
                  v-show="uploadBtnShow"
                  @click="showUploadModal(item, false)"
                >
                  <a-icon type="upload" />&nbsp;上传</a
                >
              </div>
              <!-- <a-upload :class="uploadBtnShow ? 'upload-style' : 'upload-style-hidden'" :accept="acceptFileType" :data="item" :customRequest="uploadMaterial"
                        :beforeUpload="(file) => beforeUpload(file)" :remove="handleRemove" @preview="fileView"  :showUploadList="false" name="file" multiple>
                <a-button v-show="uploadBtnShow"> <a-icon type="upload" />上传</a-button>
              </a-upload> -->

              <div class="upload_list_div" v-for="(fileItem, index) in item.fileList" :key="index">
                <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
                  <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
                  <a
                    type="link"
                    class="upload_list_item_name beyond_hiding"
                    :title="fileItem.filename"
                    :key="index"
                    @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                    @dblclick.prevent="handleDoubleClick(fileItem, index)"
                  >
                    <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                    <input
                      :ref="`input${index}`"
                      v-show="fileItem.isEditor"
                      type="text"
                      class="transparent-input"
                      v-model="newFilename"
                      :key="index"
                      ref="inputRef"
                      autofocus
                      @blur="saveFileName(fileItem)"
                      @keydown.enter="saveFileName(fileItem)"
                    />

                    <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
                  </a>
                  <a-dropdown :trigger="['click']">
                    <a
                      class="ant-dropdown-link"
                      style="display: inline-block; width: 70px; color: #000"
                      @click="e => e.preventDefault()"
                      >操作<a-icon type="down" style="padding-left: 10px"
                    /></a>
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                      </a-menu-item>
                      <!-- <a-menu-item>
                        <a style="display: block" @click="fileView(fileItem)">预览</a>
                      </a-menu-item> -->
                      <a-menu-item>
                        <a style="display: block" @click="handleRemove(fileItem)">删除</a>
                      </a-menu-item>
                      <a-menu-item>
                        <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)">在线编辑</a>
                      </a-menu-item>
                      <a-menu-item>
                        <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </a>
              </div>
            </div>
            <div v-else-if="item.isSaved && !item.isUpdated">
              <span style="padding-right: 10px"></span>
              <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
              <div class="file_title">
                <span class="upload_span">
                  {{ item.fileName }}
                  <!-- <a style="margin-left:40px" type="link" @click="editCustomerMaterial(item)">编辑</a> -->
                  <a
                    style="color: #0072c6"
                    class="upload_btn"
                    v-show="uploadBtnShow && item.isSaved"
                    @click="showUploadModal(item, true)"
                  >
                    <a-icon type="upload" />上传</a
                  >
                  <a-icon
                    :style="{ color: '#0072c6' }"
                    class="customer_icon"
                    style="margin-left: 20px"
                    @click="editCustomerMaterial(item)"
                    type="edit"
                  />
                  <span style="color: #0072c6">编辑</span>
                  <a-popconfirm
                    title="确认删除自定义材料项吗？"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="deleteCustomer(item)"
                    class="left_icon"
                  >
                    <a-icon
                      class="customer_icon"
                      :style="{ color: '#0072c6' }"
                      style="margin-left: 20px"
                      type="delete"
                    />
                    <span style="color: #0072c6">删除</span>
                  </a-popconfirm>
                </span>
              </div>
              <!-- <a-upload :class="uploadBtnShow ? 'upload-style' : 'upload-style-hidden'" :accept="acceptFileType" :data="item" :customRequest="uploadMaterialCustomer"
                        :beforeUpload="(file) => beforeUpload(file)" :remove="handleRemove" @preview="fileView" :fileList="item.fileList" :showUploadList="false" name="file" :multiple="true">
                <a-button v-show="uploadBtnShow && item.isSaved"> <a-icon type="upload" />上传</a-button>
              </a-upload> -->

              <div class="upload_list_div" v-for="(fileItem, index) in item.fileList" :key="index">
                <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
                  <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
                  <a
                    type="link"
                    class="upload_list_item_name beyond_hiding"
                    :title="fileItem.filename"
                    :key="index"
                    @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                    @dblclick.prevent="handleDoubleClick(fileItem, index)"
                  >
                    <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                    <input
                      :ref="`input${index}`"
                      v-show="fileItem.isEditor"
                      type="text"
                      class="transparent-input"
                      v-model="newFilename"
                      :key="index"
                      ref="inputRef"
                      autofocus
                      @blur="saveFileName(fileItem)"
                      @keydown.enter="saveFileName(fileItem)"
                    />

                    <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
                  </a>
                  <a-dropdown :trigger="['click']">
                    <a
                      class="ant-dropdown-link"
                      style="display: inline-block; width: 70px; color: #000"
                      @click="e => e.preventDefault()"
                      >操作<a-icon type="down" style="padding-left: 10px"
                    /></a>
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                      </a-menu-item>
                      <!-- <a-menu-item>
                        <a style="display: block" @click="fileView(fileItem)">预览</a>
                      </a-menu-item> -->
                      <a-menu-item>
                        <a style="display: block" @click="handleRemove(fileItem)">删除</a>
                      </a-menu-item>
                      <a-menu-item>
                        <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)">在线编辑</a>
                      </a-menu-item>
                      <a-menu-item>
                        <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </a>
              </div>
            </div>
            <div class="customer_div" v-else-if="!item.isSaved || item.isUpdated">
              <span class="customer_span"> {{ !item.isSaved ? '新增:' : '修改:' }}</span>
              <a-input
                class="customer_input"
                ref="userNameInput"
                v-model="item.fileName"
                placeholder="请输入自定义材料名称"
                :max-length="50"
              >
                <a-icon slot="prefix" type="file-add" />
                <a-tooltip slot="suffix" title="材料名称长度上限50">
                  <a-icon type="info-circle" style="color: rgba(0, 0, 0, 0.45)" />
                </a-tooltip>
              </a-input>
              <div class="customer_icon_group">
                <a-popconfirm
                  title="确认撤销吗？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="rollBackCustomerMaterial(item)"
                  class="left_icon"
                >
                  <a-icon class="customer_icon" type="close" />
                </a-popconfirm>
                <a-popconfirm
                  title="确认保存吗？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="saveCustomerMaterial(item)"
                  class="left_icon"
                >
                  <a-icon class="customer_icon" style="margin-left: 20px" type="check" />
                </a-popconfirm>
              </div>
            </div>
          </span>
        </a-list-item-meta>
      </a-list-item>
    </a-list>
    <MultiUploadProduce
      ref="multiUploadProduce"
      :applyid="applyid"
      :busiType="busiType"
      :currentUser="currentUser"
      @afterUpload="queryMaterialsList"
    ></MultiUploadProduce>
    <MaterialVersion ref="materialVersionRef"></MaterialVersion>
  </a-card>
</template>
<script>
import { getAllMaterialByApplyId } from '@/api/accept/aprv_process_materials'
import { queryCustomerMaterialByApplyid } from '@/api/accept/aprv_materials_customer'
import { Tp_proctypeValue } from '@/enumeration/Tp_proctype'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'
import { ProcedureMinxin } from '../ProcedureMinxin'
import { updateTargetReply } from '@/api/accept/apl_admreview'
import { getTargetListByApplyid } from '@/api/accept/apl_target'
// 默认当前的类型是被申请人回复类型
const currentProctype = Tp_proctypeValue.HEAR_REPLY
export default {
  mixins: [ProcedureMinxin],
  data () {
    return {
      operateBtnDisabled: true, // 特殊情况限制按钮
      targetOrgData: [], // 组织树层级数据
      selectPersons: undefined, // 选中的人员
      selectPersonIds: [],
      btnDisabled: true
    }
  },
  created () {
    console.log('busikey' + this.busiKey)
    this.initParam()
    this.getTargetOrg()
  },
  mounted () {},
  watch: {
    selectPersons: {
      handler (val) {
        if (this.selectPersons && this.selectPersons.length > 0) {
          this.btnDisabled = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async getTargetOrg () {
      const res = await getTargetListByApplyid(this.applyid)
      if (res.code === 0) {
        this.targetOrgData = res.data ? res.data : []
      } else {
        this.$message.error('查询组织机构异常')
      }
    },
    initParam () {
      // 通过传入的类型来获取对应的数据
      this.resetMaterialType()
    },
    onSelect (selectedKeys, e) {
      this.selectPersonIds.push(e.eventKey)
    },
    async resetMaterialType () {
      // 通过传入的类型来获取对应的数据
      this.fileItem = []
      this.typeEnum = {}
      for (const key in this.Tp_proctypeEnum) {
        if (this.Tp_proctypeEnum[key].value === this.busiKey) {
          this.typeEnum = this.Tp_proctypeEnum[key]
        }
      }
      this.labelTitle = this.typeEnum.name
      const material = this.typeEnum.material
      this.busiType = this.typeEnum.value
      this.busiName = this.typeEnum.key
      this.setButtonDisabled()
      for (const index in material) {
        const fileItem = {
          fileName: material[index].name,
          fileType: material[index].value,
          isMultiUpload: true,
          fileList: [],
          required: material[index].required,
          isCustomer: false,
          isSaved: true,
          isUpdated: false
        }
        this.fileItem.push(fileItem)
      }
      // 查询对应applyid的自定义材料类型
      const res = await queryCustomerMaterialByApplyid({ applyid: this.applyid })
      if (res.code == 0) {
        const customerMaterials = res.data
        for (const index in customerMaterials) {
          // 如果当前的自定义材料的类型和当前的业务类型一直才展示该自定义类型材料
          this.customerMaterials = customerMaterials.filter(item => item.proctype == this.busiType)
          if (customerMaterials[index].proctype == this.busiType) {
            const customerFileItem = {
              fileName: customerMaterials[index].name,
              fileType: Tp_procmaterialValue.MATER_CUSTOMER,
              replyCustomerId: customerMaterials[index].id,
              isMultiUpload: true,
              fileList: [],
              required: false,
              isCustomer: true,
              isSaved: true,
              isUpdated: false,
              sortnum: customerMaterials[index].sortnum
            }
            this.fileItem.push(customerFileItem)
          }
        }
      } else {
        console.log('查询自定义材料错误...')
      }
      this.queryMaterialsList()
    },

    setButtonDisabled () {
      if (this.isEditModel) {
        if (this.busiName == this.Tp_proctypeEnum.hear_reply.key) {
          // 审理-非被申请人答复才需要不隐藏按钮
          this.operateBtnShow = true // 操作按钮展示
          this.uploadBtnShow = true // 上传按钮展示
          if (this.fileItem != null && this.fileItem.length > 0 && this.fileItem[0].fileList.length > 0) {
            this.operateBtnDisabled = false
          } else {
            this.operateBtnDisabled = true
          }
        }
      } else {
        this.operateBtnShow = false
        this.uploadBtnShow = false
      }
      // FIXME: 临时放开
      this.uploadBtnShow = true
    },
    /**
     * 查询对应的applyid下有多少材料文件
     */
    queryMaterialsList () {
      this.queryParam.applyid = this.applyid
      const _this = this
      this.loading = true
      getAllMaterialByApplyId(this.queryParam)
        .then(res => {
          // console.log('表格数据:', res.data)
          const records = res.data
          // 根据对应的分类进行赋值
          for (let index = 0; index < _this.fileItem.length; index++) {
            _this.fileItem[index].fileList = []
            if (records != null && records.length > 0) {
              // 非自定义材料
              for (const record of records) {
                if (this.fileItem[index].fileType != Tp_procmaterialValue.MATER_CUSTOMER) {
                  if (record.mattype == _this.fileItem[index].fileType && record.type == this.busiType) {
                    const fileDetail = record.file
                    fileDetail.materialId = record.id
                    fileDetail.name = fileDetail.filename
                    fileDetail.status = 'done'
                    fileDetail.uid = fileDetail.id
                    fileDetail.url = fileDetail.path
                    _this.fileItem[index].fileList.push(fileDetail)
                  }
                } else {
                  if (record.reply_attachid == this.fileItem[index].replyCustomerId && record.type == this.busiType) {
                    const fileDetail = record.file
                    fileDetail.materialId = record.id
                    fileDetail.name = fileDetail.filename
                    fileDetail.status = 'done'
                    fileDetail.uid = fileDetail.id
                    fileDetail.url = fileDetail.path
                    fileDetail.reply_attachid = record.reply_attachid
                    _this.fileItem[index].fileList.push(fileDetail)
                  }
                }
              }
            }
          }
          this.setButtonDisabled()
        })
        .catch(err => {
          console.log(err, '获取数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    activeBtnClick () {
      // 若是被申请人答复，特殊情况直接cofirm提醒
      this.modalVisible = false
      this.$confirm({
        title: '提示',
        content: '是否确认已收到申请人答复',
        onOk: () => {
          // 通过applyid 更新数据
          this.updateTargetReply(true, 'hear_reply')
        },
        onCancel: () => {}
      })
    },
    updateTargetReply (status, category) {
      updateTargetReply({ applyid: this.applyid, reply: status }).then(res => {
        if (res.code == 0) {
          this.$message.success('操作成功')
        } else {
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/apply/caseProcedure.scss';
</style>

<style lang="less" scoped>
.file_list {
  min-height: 200px;
}

.file_icon {
  font-size: 25px;
}

.file_button {
  display: inline-block;
  margin-right: 20px;
}

.customer_div {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 20px;
}

.customer_span {
  width: 60px;
  font-size: 18px;
}

.customer_input {
  width: 400px;
}

.customer_icon_group {
  margin-left: 30px;
}

.customer_icon {
  font-size: 18px;
  cursor: pointer;
}

.upload-style {
  padding-left: 450px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }
}

.upload-style-hidden {
  padding-left: 320px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }

  ::v-deep .ant-upload-list-item-card-actions {
    display: none;
  }
}

.div_center {
  display: flex;
  /*开启flex布局*/
  justify-content: center;
  /*水平居中*/
  align-items: center;
  /*垂直居中*/
  height: 100%;
  /*设置高度*/
}

.progress_success_btn {
  margin-right: 150px;
}

.progress_fail_btn {
  margin-left: 150px;
}

.add_form_btn {
  display: block;
  float: right;
  margin-right: 20px;
}

.add_form_label {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

::v-deep .ant-upload-list-text {
  width: 550px;
}
::v-deep .ant-form-item-label {
  > label {
    font-size: 16px;
  }
}
.transparent-input {
  background-color: transparent; /* 设置背景透明 */
  border: none; /* 移除边框 */
  border-bottom: 1px solid rgb(251, 251, 252); /* 可选：添加底部边框以提升可视度 */
  outline: none; /* 移除默认的输入框外观 */
  color: rgb(119, 166, 253); /* 设置文本颜色 */
  /* 可以根据需要添加更多样式 */
}
.case_produce {
  .upload_list_div {
    // width: 70% !important;
  }
}
</style>
